package com.st.service.impl;

import com.st.common.enums.UserStatus;
import com.st.core.entity.LoginRequest;
import com.st.core.entity.constant.ErrorConstants;
import com.st.core.entity.exception.ApplicationRuntimeException;
import com.st.domain.SysUser;
import com.st.mapper.SysRoleMapper;
import com.st.mapper.SysUserMapper;
import com.st.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 认证
 *
 * @author shent
 */
@Service
@Slf4j
public class AuthServiceImpl implements AuthService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public Boolean login(LoginRequest loginRequest) {
        SysUser sysUser = sysUserMapper.selectUsernameUseful(loginRequest.getUsername());
        if (sysUser == null) {
            log.error("用户名不存在");
            throw new ApplicationRuntimeException(ErrorConstants.ERROR_USERNAME_PASSWORD_NOT_MATCH);
        }
        boolean isMatched = passwordEncoder.matches(loginRequest.getPassword(), sysUser.getPassword());
        if (!isMatched) {
            log.error("密码不匹配");
            throw new ApplicationRuntimeException(ErrorConstants.ERROR_USERNAME_PASSWORD_NOT_MATCH);
        }
        if (sysUser.getStatus() == UserStatus.FORBIDDEN.getValue()) {
            log.error("用户登录已过期");
            throw new CredentialsExpiredException(ErrorConstants.ERROR_USER_DISABLED);
        }
        return true;
    }
}
